package chpt03.shopping;

public class ShoppingCart {
    private Commodity[] items; // 使用数组存放商品
    private int count; // 记录购物车中商品数量
    private final int capacity; // 购物车的初始容量

    public ShoppingCart(int capacity) {
        items = new Commodity[capacity]; // 初始化数组大小为初始容量
        count = 0;
        this.capacity = capacity;
    }

    public void add(Commodity c) {
    	if (c == null || count >= capacity) {
            return; // e为空或大于等于最大容量不能添加
        }
        items[count] = c; // 将商品添加到数组中
        count++;
    }

    public void show() {
    	for (Commodity e : items) {
    		printCommodity(e);
		}
    }

    private void printCommodity(Commodity commodity) {
        System.out.printf("name: %s, price: %f%n", 
        		commodity.getName(), commodity.getPrice());
    }

    public boolean delete(Commodity c) {
        for (int i = 0; i < count; i++) {
            if (items[i].getName().equals(c.getName())) {
                // 将后面的商品往前移动一个位置
                for (int j = i; j < count - 1; j++) {
                    items[j] = items[j + 1];
                }
                items[count - 1] = null; // 将最后一个位置置为null
                count--;
                return true;
            }
        }
        return false;
    }

    public void clear() {
        items = new Commodity[capacity]; // 清空数组并重新初始化大小为初始容量
        count = 0;
    }

    public double checkout() {
        double total = 0;
        for (int i = 0; i < count; i++) {
            total += items[i].getPrice();
        }
        return total;
    }

    public int getQty() {
        return count;
    }
}